#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/1/10 8:34
# @Author  : afraidbenq
# @File    : config_generator.py
# @Software: PyCharm
# @Github  : github/afraidbenq
# @Email   : 329189987@qq.com
# @Desc    :
"""
pytest conftest配置文件生成器（包括__init__.py、conftest.py）
"""
import os
import datetime

from config import Config
from custom.myexceptions import ValueNotFoundError


class ConfTestGeneration:
    def __init__(self, project_name):
        self.conftest_path = os.path.join(Config.case_script_path, project_name)
        self.project_name = project_name
        # print(self.conftest_path)
        self.now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        self.real_time_update_conftest = Config.project[self.project_name]["real_time_update_conftest"]
        self.gen_init_file()
        self.gen_conftest_file()

    def write_file(self, file_path, file_data):
        """ 写入文件 """
        with open(file_path, 'w', encoding="utf-8") as file:
            file.write(file_data)

    def gen_init_file(self):
        init_file = f'''#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 


import os

from config import Config
from util.generator.case_verification import CaseData
from util.file import get_all_files
from util.cache.cache_control import CacheHandler, _cache_config


def write_case_process():
    """
    获取所有用例，写入用例池中
    :return:
    """
    print(f" __init__.py 初始化获取到项目{self.project_name}下所有用例，写入用例池中：")
    for i in get_all_files(file_path=os.path.join(Config.data_path, "{self.project_name}"), yaml_data_switch=True):
        print(i)
        # 循环读取文件中的数据
        case_process = CaseData(i).case_process(case_id_switch=True)
        if case_process is not None:
            # 转换数据类型
            for case in case_process:
                for k, v in case.items():
                    # 判断 case_id 是否已存在
                    case_id_exit = k in _cache_config.keys()
                    # 如果case_id 不存在，则将用例写入缓存池中
                    if case_id_exit is False:
                        CacheHandler.update_cache(cache_name=k, value=v)
                        # case_data[k] = v
                    # 当 case_id 为 True 存在时，则跑出异常
                    elif case_id_exit is True:
                        raise ValueError(f"case_id: {{k}} 存在重复项, 请修改case_id"
                                         f"文件路径: {{i}}")
    # 将项目配置写入缓存池中
    for k, v in Config.project["{self.project_name}"].items():
        CacheHandler.update_cache(cache_name=k, value=v)


write_case_process()
        '''
        file_path = os.path.join(self.conftest_path, "__init__.py")
        if self.real_time_update_conftest:
            self.write_file(file_path=file_path, file_data=init_file)
        elif self.real_time_update_conftest is False:
            if not os.path.exists(file_path):
                self.write_file(file_path=file_path, file_data=init_file)
        else:
            raise ValueNotFoundError("real_time_update_conftest 配置不正确，只能配置 True 或者 False")

    def gen_conftest_file(self):
        conftest_file = f'''#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time   : 


import time
import ast

import pytest
import allure
import requests

from common import logger
from config import Config
from util.requests.request_control import cache_regular
from config.models import TestCase
from util.file import del_file
from util.allure.allure_tools import allure_step, allure_step_no
from util.cache.cache_control import CacheHandler

print("读取conftest配置")


@pytest.fixture(scope="session", autouse=False)
def clear_report():
    """如clean命名无法删除报告，这里手动删除"""
    logger.info("清除报告")
    del_file(Config.report_path + "tmp")


@pytest.fixture(scope="session", autouse=True)
def login():
    """
    获取登录的token
    :return:
    """
    logger.info("获取登录token")
    CacheHandler.update_cache(cache_name='token', value=None)


@pytest.fixture(scope="function", autouse=True)
def case_skip(in_data):
    """处理跳过用例"""
    in_data = TestCase(**in_data)
    if ast.literal_eval(cache_regular(str(in_data.is_run))) is False:
        allure.dynamic.title(in_data.detail)
        allure_step_no(f"请求URL: {{in_data.is_run}}")
        allure_step_no(f"请求方式: {{in_data.method}}")
        allure_step("请求头: ", in_data.headers)
        allure_step("请求数据: ", in_data.data)
        allure_step("依赖数据: ", in_data.dependence_case_data)
        allure_step("预期数据: ", in_data.assert_data)
        pytest.skip()
                '''
        file_path = os.path.join(self.conftest_path, "conftest.py")
        if self.real_time_update_conftest:
            self.write_file(file_path=file_path, file_data=conftest_file)
        elif self.real_time_update_conftest is False:
            if not os.path.exists(file_path):
                self.write_file(file_path=file_path, file_data=conftest_file)
        else:
            raise ValueNotFoundError("real_time_update_conftest 配置不正确，只能配置 True 或者 False")


if __name__ == '__main__':
    ConfTestGeneration("pay")
